package com.ffcc.fitness.websocket.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ffcc.fitness.websocket.config.WebSocketTokenConfigurator;
import com.ffcc.fitness.websocket.pojo.Message;
import com.ffcc.fitness.websocket.service.ChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * WebSocket处理器
 */
@Component
@ServerEndpoint(value = "/websocket/chat/{userId}", configurator = WebSocketTokenConfigurator.class)
public class WebSocketHandler {
    
    // 存储用户连接
    private static final Map<Long, Session> USER_SESSIONS = new ConcurrentHashMap<>();
    
    // 注入服务（需要特殊处理，因为WebSocket不是Spring管理的）
    private static ChatService chatService;
    private static ObjectMapper objectMapper = new ObjectMapper();
    
    @Autowired
    public void setChatService(ChatService chatService) {
        WebSocketHandler.chatService = chatService;
    }    /**
     * 连接建立
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") Long userId) {
        try {
            System.out.println("=== WebSocket连接尝试开始 ===");
            System.out.println("用户ID: " + userId);
            System.out.println("Session ID: " + session.getId());
            System.out.println("Request URI: " + session.getRequestURI());
            System.out.println("用户属性: " + session.getUserProperties());
            
            // 暂时跳过token验证，直接建立连接
            USER_SESSIONS.put(userId, session);
            System.out.println("=== 用户 " + userId + " 连接WebSocket成功（无token验证）===");
            
            // 发送连接成功消息
            String welcomeMsg = "{\"type\":\"connect\",\"status\":\"success\",\"message\":\"连接成功\"}";
            session.getBasicRemote().sendText(welcomeMsg);
            
        } catch (Exception e) {
            System.err.println("=== WebSocket连接失败 ===");
            System.err.println("用户ID: " + userId);
            System.err.println("错误信息: " + e.getMessage());
            e.printStackTrace();
            try {
                session.close(new CloseReason(CloseReason.CloseCodes.UNEXPECTED_CONDITION, "Connection failed"));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
    
    /**
     * 连接关闭
     */
    @OnClose
    public void onClose(@PathParam("userId") Long userId) {
        USER_SESSIONS.remove(userId);
        System.out.println("用户 " + userId + " 断开WebSocket连接");
    }
    
    /**
     * 接收消息
     */
    @OnMessage
    public void onMessage(String messageStr, @PathParam("userId") Long fromId) {        try {
            // 解析消息
            @SuppressWarnings("unchecked")
            Map<String, Object> messageData = objectMapper.readValue(messageStr, Map.class);
            Long toId = Long.valueOf(messageData.get("toId").toString());
            String content = messageData.get("content").toString();
            
            // 保存消息到数据库
            Message message = chatService.sendMessage(fromId, toId, content);
            
            // 发送消息给接收者
            Session toSession = USER_SESSIONS.get(toId);
            if (toSession != null && toSession.isOpen()) {
                String responseMessage = objectMapper.writeValueAsString(message);
                toSession.getBasicRemote().sendText(responseMessage);
            }
            
            // 确认消息发送给发送者
            Session fromSession = USER_SESSIONS.get(fromId);
            if (fromSession != null && fromSession.isOpen()) {
                Map<String, Object> ack = Map.of(
                    "type", "ack",
                    "messageId", message.getMessageId(),
                    "status", "sent"
                );
                String ackMessage = objectMapper.writeValueAsString(ack);
                fromSession.getBasicRemote().sendText(ackMessage);
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 错误处理
     */
    @OnError
    public void onError(Session session, Throwable error, @PathParam("userId") Long userId) {
        System.err.println("用户 " + userId + " WebSocket连接错误: " + error.getMessage());
        error.printStackTrace();
    }
    
    /**
     * 发送消息给指定用户
     */
    public static void sendMessageToUser(Long userId, String message) {
        Session session = USER_SESSIONS.get(userId);
        if (session != null && session.isOpen()) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }    /**
     * 检查用户是否在线
     */
    public static boolean isUserOnline(Long userId) {
        Session session = USER_SESSIONS.get(userId);
        return session != null && session.isOpen();
    }
}
